package vn.edu.ptithcm.pim.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import vn.edu.ptithcm.pim.common.bean.PaginationObject;
import vn.edu.ptithcm.pim.constant.Constants;
import vn.edu.ptithcm.pim.constant.Paginations;
import vn.edu.ptithcm.pim.constant.TaskStatuses;
import vn.edu.ptithcm.pim.constant.UrlConstants;
import vn.edu.ptithcm.pim.dom.Project;
import vn.edu.ptithcm.pim.dom.Task;
import vn.edu.ptithcm.pim.service.ProjectService;
import vn.edu.ptithcm.pim.service.TaskService;
import vn.edu.ptithcm.pim.service.UserService;
import vn.edu.ptithcm.pim.util.ParamUtil;

@SuppressWarnings("deprecation")
public class ShowTaskListController extends SimpleFormController {
	private TaskService taskService;
	private UserService userService;
	private ProjectService projectService;

	Logger log = Logger.getLogger(ShowTaskListController.class);

	public ShowTaskListController() {
		super();
		setSessionForm(true);
		setCommandClass(Object.class);
		setFormView(UrlConstants.TASKS_URL);
		setSuccessView(UrlConstants.TASKS_URL);
	}

	@Override
	public void initBinder(HttpServletRequest request,
			ServletRequestDataBinder binder) throws Exception {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		binder.registerCustomEditor(Date.class, new CustomDateEditor(
				dateFormat, true));
	}

	@Override
	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		return showForm(request, response, errors);
	}

	@SuppressWarnings("unchecked")
	@Override
	protected ModelAndView showForm(HttpServletRequest request,
			HttpServletResponse response, BindException errors)
			throws Exception {
		Map<String, Object> bean = new HashMap<String, Object>();
		if (userService.isSignedIn(request)) {
			String loginName = userService.getCurrentLogin(request);
			bean.put("user", userService.findByLoginName(loginName));
			bean.put("isSigned", true);
			bean.put("isAdmin", userService.isAdmin(loginName));
			bean.put(Constants.LOGIN_NAME, loginName);
			bean.put(Constants.USER_NAME, userService.getUsername(loginName));
			String visa = userService.getVisa(loginName);
			bean.put("visa", visa);

			int pnum = ParamUtil.getInteger(request, "pnum", 0);
			Project project = projectService.findByNumber(pnum);
			if (project != null) {
				bean.put("project", project);
				bean.put("tab", "tasks");

				Map<String, String> taskTypes = new HashMap<String, String>();
				taskTypes.put(Constants.UN_RESOLVED_TASKS,
						"project.task.unresolved");
				taskTypes.put(Constants.NEW_TASKS, "project.task.unassigned");
				taskTypes.put(Constants.REPORTED_BY_ME_TASKS,
						"project.task.reported.by.me");
				taskTypes
						.put(Constants.RESOLVED_TASKS, "project.task.resolved");
				taskTypes.put(Constants.RECENTLY_MODIFIED_TASKS,
						"project.task.recently.modified");
				taskTypes.put(Constants.MORNITORED_BY_ME_TASKS,
						"project.task.montored.by.me");
				taskTypes.put(Constants.DELAY_TASKS, "project.task.delay");

				int currentPage = ParamUtil.getInteger(request,
						Paginations.CURRENT_PAGE_NUM, 1);
				int pageSize = ParamUtil.getInteger(request,
						Paginations.PAGE_SIZE, Paginations.ITEMS_PER_PAGE);
				String type = ParamUtil.getString(request, "type", "all");

				List<Task> tasks = new ArrayList<Task>(0);
				PaginationObject paging = null;
				int total = 0;
				if (type.equals(Constants.UN_RESOLVED_TASKS)) {
					total = projectService.countUnResolvedTasks(
							project.getProjectid(), visa);
					paging = new PaginationObject(Constants.UN_RESOLVED_TASKS
							+ "Paging", total);

					paging.paging(currentPage, pageSize);

					int max = paging.getEndIndex() - paging.getStartIndex();
					tasks.addAll(projectService.getUnResolvedTasks(visa,
							project.getProjectid(), max, paging.getStartIndex()));

				} else if (type.equals(Constants.NEW_TASKS)) {
					total = projectService.countTasksByStatus(new Long(
							TaskStatuses.NEW), project.getProjectid());
					paging = new PaginationObject(Constants.NEW_TASKS
							+ "Paging", total);

					paging.paging(currentPage, pageSize);

					int max = paging.getEndIndex() - paging.getStartIndex();
					tasks.addAll(projectService.getTasksByStatus(new Long(
							TaskStatuses.NEW), project.getProjectid(), max,
							paging.getStartIndex()));

				} else if (type.equals(Constants.REPORTED_BY_ME_TASKS)) {
					total = projectService.countReportedByMeTasks(
							project.getProjectid(), visa);
					paging = new PaginationObject(
							Constants.REPORTED_BY_ME_TASKS + "Paging", total);

					paging.paging(currentPage, pageSize);

					int max = paging.getEndIndex() - paging.getStartIndex();
					tasks.addAll(projectService.getReportedByMeTasks(
							project.getProjectid(), visa, max,
							paging.getStartIndex()));

				} else if (type.equals(Constants.RECENTLY_MODIFIED_TASKS)) {
					total = projectService.countRecentlyModifiedTasks(project
							.getProjectid());
					paging = new PaginationObject(
							Constants.RECENTLY_MODIFIED_TASKS + "Paging", total);

					paging.paging(currentPage, pageSize);

					int max = paging.getEndIndex() - paging.getStartIndex();
					tasks.addAll(projectService.getRecentlyModifiedTasks(
							project.getProjectid(), max, paging.getStartIndex()));

				} else if (type.equals(Constants.RESOLVED_TASKS)) {
					total = projectService.countTasksByStatus(new Long(
							TaskStatuses.RESOLVED), project.getProjectid());
					paging = new PaginationObject(Constants.RESOLVED_TASKS
							+ "Paging", total);

					paging.paging(currentPage, pageSize);

					int max = paging.getEndIndex() - paging.getStartIndex();
					tasks.addAll(projectService.getTasksByStatus(new Long(
							TaskStatuses.RESOLVED), project.getProjectid(),
							max, paging.getStartIndex()));

				} else if (type.equals(Constants.MORNITORED_BY_ME_TASKS)) {
					total = projectService.countMonitoredByMeTasks(
							project.getProjectid(), visa);
					paging = new PaginationObject(
							Constants.MORNITORED_BY_ME_TASKS + "Paging", total);

					paging.paging(currentPage, pageSize);

					int max = paging.getEndIndex() - paging.getStartIndex();
					tasks.addAll(projectService.getMonitoredByMeTasks(
							project.getProjectid(), visa, max,
							paging.getStartIndex()));

				} else if (type.equals(Constants.DELAY_TASKS)) {
					total = projectService.countDelayTasks(project
							.getProjectid());
					paging = new PaginationObject(Constants.DELAY_TASKS
							+ "Paging", total);

					paging.paging(currentPage, pageSize);

					int max = paging.getEndIndex() - paging.getStartIndex();
					tasks.addAll(projectService.getDelayTasks(
							project.getProjectid(), max, paging.getStartIndex()));

				} else {
					total = taskService.countFilterByProjectId(project
							.getProjectid());
					paging = new PaginationObject("filterPaging", total);

					paging.paging(currentPage, pageSize);

					int max = paging.getEndIndex() - paging.getStartIndex();
					tasks.addAll(taskService.filterByProjectId(
							project.getProjectid(), max, paging.getStartIndex()));
				}

				bean.put("paging", paging);
				bean.put("total", total);
				bean.put("pagingUrl", request.getRequestURL().toString()
						+ "?pnum=" + pnum);
				bean.put("taskTypes", taskTypes);
				bean.put("type", type);
				bean.put("tasksCount", tasks.size());
				bean.put("tasks", tasks);
				bean.put("itemsPerPage", Paginations.ITEMS_PER_PAGE);

			}

		} else {
			int pnum = ParamUtil.getInteger(request, "pnum", 0);
			String redirectLink = UrlConstants.TASKS_URL + UrlConstants.HTM
					+ "?pnum=" + pnum;
			request.getSession().setAttribute("redirectLink", redirectLink);
			response.sendRedirect(UrlConstants.HOME_PAGE_URL + UrlConstants.HTM);
		}
		request.setAttribute("bean", bean);
		return super.showForm(request, response, errors);
	}

	public ProjectService getProjectService() {
		return projectService;
	}

	public void setProjectService(ProjectService projectService) {
		this.projectService = projectService;
	}

	public TaskService getTaskService() {
		return taskService;
	}

	public void setTaskService(TaskService taskService) {
		this.taskService = taskService;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

}
